package com.wr.factory;

import com.wr.annotation.Autowired;
import com.wr.annotation.Component;
import com.wr.utils.TransationManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 王瑞
 * @descreption:  生成动态代理对象的类
 * @date 2020/2/16  0:07
 */
@Component
public class ProxyInstanceFactory {

    @Autowired
    private TransationManager transationManager;

    public void setTransationManager(TransationManager transationManager) {
        this.transationManager = transationManager;
    }

    //jdk动态代理
    public Object creatProxyInstanceJdk(Object obj) {
        Object o = Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Exception {

                Object invoke = null;
                try {
                    //添加事务管理
                    transationManager.startTransation();
                    invoke = method.invoke(obj, objects);
                    transationManager.commitTransation();

                } catch (Exception e) {
                    e.printStackTrace();
                    transationManager.rollbackTransation();//异常时事务回滚
                    throw e;
                }
                return invoke;
            }
        });
        return o;
    }

    //Cglib动态代理
    public Object creatProxyInstanceCglib(Object obj) {
        Object o = Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Exception {
                Object invoke = null;
                try {
                    //添加事务管理
                    transationManager.startTransation();
                    invoke = method.invoke(obj, objects);
                    transationManager.commitTransation();
                } catch (Exception e) {
                    e.printStackTrace();
                    transationManager.rollbackTransation();//异常时事务回滚
                    throw e;
                }
                return invoke;
            }
        });
        return o;
    }


}
